package com.itheima.kafka.demo.consume;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * 消费者
 */
public class ConsumerQuickStart100 {

    public static void main(String[] args) {
        //1.添加kafka的配置信息
        Properties properties = new Properties();
        //kafka的连接地址
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        //消费者组
        //同一个组下的消费组订阅同一个主题，那么他们共同消费这个主题下的消息，一个消息只能被一个消费者取走
        //如果是不同组下的消费组订阅同一个主题，消息可以同时被消费者共同消费
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "group1");
        //消息的反序列化器
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");



        //2.消费者对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);


        //3.订阅主题
//        consumer.subscribe(Collections.singletonList("itheima-topic-testpartition"));



        //负责处理itheima-topic-testpartition主题下的1号分区
        TopicPartition topicPartition = new TopicPartition("itheima-topic-testpartition",1);
        consumer.assign(Collections.singletonList(topicPartition));

        //当前线程一直处于监听状态
        while (true) {
            //4.获取消息
            ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofMillis(1000));
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                System.out.println(consumerRecord.key());//消息的key
                System.out.println(consumerRecord.value());//消息的value
                System.out.println(consumerRecord.topic());//主题
                System.out.println(consumerRecord.partition());//分区
                System.out.println(consumerRecord.offset());//偏移量  消息在某一个主题下的分区下的  下标
                System.out.println("--------------");
            }
        }

    }

}